package org.csu.mypetstore.service.impl;

import ch.qos.logback.classic.Logger;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.persistence.ItemMapper;
import org.csu.mypetstore.persistence.ProductMapper;
import org.csu.mypetstore.service.ItemService;
import org.csu.mypetstore.vo.ItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public Item getItemById(String itemId) {
        Item item=itemMapper.selectItemById(itemId);
        return item;
    }

    @Override
    public int getInventoryQuantity(String itemId) {
        return itemMapper.selectInventoryQuantity(itemId);
    }

    @Override
    public List<Item> getItemsByProductId(String productId) {
        return itemMapper.selectItemsByProductId(productId);
    }

    @Override
    public void addItem(Item item) {
        // 确保 supplierId 有效
        if (item.getSupplierId() ==null || !isValidSupplier(item.getSupplierId())) {
            throw new IllegalArgumentException("Invalid supplier ID");
        }
        else  itemMapper.insertItem(item);

    }

    @Override
    public void updateItem(Item item) {
        // 确保 supplierId 有效
        if (item.getSupplierId() == null || !isValidSupplier(item.getSupplierId())) {
            throw new IllegalArgumentException("Invalid supplier ID");
        }
        itemMapper.updateItem(item);
    }

    @Override
    public void deleteItem(String itemId) {
        itemMapper.deleteItem(itemId);
    }

    @Override
    public Product getProductById(String productId) {
        if (productId == null || productId.trim().isEmpty()) {
            return null;
        }
        return (Product) productMapper.selectProductById(productId);
    }

    //查找该itemid
    @Override
    public boolean SearchIsItemId(String itemId) {
        itemMapper.selectItemById(itemId);
        if (itemMapper.selectItemById(itemId)==null||itemMapper.selectItemById(itemId).equals(null))
        {
            return false;//添加
        }
        else return true; //更新
    }

    // 检查供应商ID是否有效
    private boolean isValidSupplier(Integer supplierId) {
        // 假设有一个方法验证供应商是否有效

        // 在实际中，你可以通过查询供应商表来验证
        return supplierId != null && supplierId > 0;  // 示例简单判断
    }
}
